package server.threads;

import java.io.IOException;
import java.util.HashMap;

import server.Connection;
import server.ConnectionMap;
import server.Server;

import message.PingRequestMessage;

public class ConnectionChecker extends Thread
{
	private final ConnectionMap connections;
	private final Server server;
	private static final int inactivityPingTime = 15000; // 15 seconds
	private static final int maxInactivityPingTime = 30000; // 30 seconds
	private boolean running = true;
	
	public ConnectionChecker(Server server, ConnectionMap connections)
	{
		this.server = server;
		this.connections = connections;
	}
	public void stopRunning()
	{
		running = false;
	}
	@Override
	public void run()
	{
		try
		{
			while (running)
			{
				Connection[] connections = this.connections.values().toArray(new Connection[0]);

				for (int i = 0; i < connections.length; i ++)
				{
					Connection connection = connections[i];
					
					if (connection.getInactivityTime() > maxInactivityPingTime)
					{
						System.out.println("Removing connection.");
						
						try
						{
							connection.close();
						}
						catch (IOException e) {}
						
						this.connections.remove(connection.connectionId);
					}
					else if (connection.getInactivityTime() > inactivityPingTime && connection.canBePinged())
					{
						System.out.println("Pinging connection.");
						PingRequestMessage message = new PingRequestMessage();
						
						connection.sendMessage(message);
					}
				}
				
				try
				{
					Thread.sleep(1000); // Pause connection checking for a second
				}
				catch (InterruptedException e) {} 
			}
		}
		catch (Throwable t) { server.uncaughtThrowableThrown(t); }
	}
}
